import { defineStore } from 'pinia'
import { LOGIN_TOKEN } from '@/global/constants'
import router from '@/router'
import { accountLoginRequest } from '../../service/login/login'
import { localCache } from '@/utils/cache'
import { getUserMenusByRoleId } from '../../service/login/login'
import { getUserInfoById } from '../../service/login/login'
import { mapMenusToRoutes, mapMenuToPermissions } from '@/utils/map-menus'
import type { RouteRecordRaw } from 'vue-router'
import useMainStore from '../main/main'
interface ILoginState {
  token: string
  userInfo: any
  userMenus: any
  permissions: string[]
}
const useLoginStore = defineStore('login', {
  state: (): ILoginState => ({
    token: '',
    userMenus: [], //写为：getCahe('userMenus')刷新之后会丢失
    userInfo: {},
    permissions: []
  }),
  actions: {
    async loginAccountAction(account: { name: string; password: string }) {
      const loginResult = await accountLoginRequest(account)//如果失败，后面代码不会执行
      const id = loginResult.data.id
      this.token = loginResult.data.token
      const name = loginResult.data.name
      localCache.setCache(LOGIN_TOKEN, this.token)
      //查询登录用户详情信息
      const userInfoResult = await getUserInfoById(id)
      this.userInfo = userInfoResult.data
      //根据用户角色请求用户权限
      const userMenusResult = await getUserMenusByRoleId(this.userInfo.role.id)
      this.userMenus = userMenusResult.data
      //本地存储
      localCache.setCache('userInfo', this.userInfo)
      localCache.setCache('userMenus', this.userMenus)
      //请求所有roles，以及department数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()
      //动态添加路由，页面刷新之后会丢失，只会执行router里面的内容
      const routes = mapMenusToRoutes(this.userMenus)
      //将新路由添加为main的子路由
      routes.forEach((route: RouteRecordRaw) => router.addRoute('main', route))
      //获取登录用户所有按钮权限
      const permissions = mapMenuToPermissions(this.userMenus)
      //保存
      this.permissions = permissions

      //页面跳转
      router.push('/main')
    },

    loadLocalCacheAction() {
      const token = localCache.getCache(LOGIN_TOKEN) ?? ''
      const userInfo = localCache.getCache('userInfo') ?? {}
      const userMenus = localCache.getCache('userMenus') ?? []
      if (token && userInfo.id && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus
        //请求所有roles，以及department数据,刷新之后会丢失，只会执行router里面的内容
        const mainStore = useMainStore()
        mainStore.fetchEntireDataAction()
        //获取登录用户所有按钮权限,保证刷新之后也会获得权限信息
        const permissions = mapMenuToPermissions(this.userMenus)
        //保存
        this.permissions = permissions

        //动态添加路由
        const routes = mapMenusToRoutes(this.userMenus)
        routes.forEach((route: RouteRecordRaw) =>
          router.addRoute('main', route)
        )
      }
    }
  }
})
export default useLoginStore
